package com.the9tcat.deliverycoming;

import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.mobclick.android.MobclickAgent;
import com.the9tcat.deliverycoming.db.DeliveryDb;
import com.the9tcat.deliverycoming.modle.DeliveryInfo;
import com.the9tcat.deliverycoming.net.HttpClient;
import com.the9tcat.deliverycoming.util.ComCode;
import com.the9tcat.deliverycoming.util.Logger;

/**
 * 
 * @author       Aliusa 
 * @class        DeliveryAddition 
 * @description  
 * @notes        
 * @copyright    Aug 9, 2011 3:06:41 PM. All rights reserved.
 */
public class DeliveryAddActivity extends Activity {
	
    private LinearLayout item_bg;
    private EditText item_name;
    private EditText item_trackingNumber;
    private Spinner item_expressCompany;
    private TextView save;
    private RadioGroup item_color;
    private DeliveryInfo delivery;
    private ImageView btn_barcode;
    private long mTrackId;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
      
        setContentView(R.layout.delivery_addition);
        bindResourceID();
        setItemColorAsDefault();
        selectExpressCompany();
        selectItemColor();
        setEnventOnSave();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }


	@Override
    protected void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);
    }
	
	/**
	 * *********************************************************
	 * @function    setSpinner      
	 * @description 
	 * @notes
	 * @author      Aliusa      
	 * @copyright   Aug 9, 2011 3:19:02 PM. All rights reserved.
	 ***********************************************************
	 */
	private void bindResourceID(){
	    
	    delivery = new DeliveryInfo();
	    save = (TextView)findViewById(R.id.button);
	    item_bg = (LinearLayout)findViewById(R.id.deliveryAddition);
	    item_color = (RadioGroup)findViewById(R.id.item_color);
	    
	    item_name = (EditText)findViewById(R.id.item_name);
	    item_trackingNumber = (EditText)findViewById(R.id.item_trackingNumber);
	    item_expressCompany = (Spinner) findViewById(R.id.item_expressCompany);
	    
	    btn_barcode = (ImageView) findViewById(R.id.btn_barcode);
	    btn_barcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DeliveryAddActivity.this, CaptureActivity.class);
                startActivityForResult(intent, 0);
            }
        });
	}
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            item_trackingNumber.setText(data.getStringExtra("barcode"));
        } catch (Exception e) {};
    }

    /**
	 * *********************************************************
	 * @function    setItemColorAsDefault      
	 * @description 
	 * @notes
	 * @author      Aliusa      
	 * @copyright   Aug 17, 2011 4:57:44 PM. All rights reserved.
	 ***********************************************************
	 */
	private void setItemColorAsDefault(){
	    final Random r = new Random();
        final int itemColor = r.nextInt(3)+1;
        switch(itemColor){
            case DeliveryInfo.COLOR_BLUE:
                item_bg.setBackgroundResource(R.drawable.bg_blue);
                item_color.check(R.id.item_color_blue);
                break;
            case DeliveryInfo.COLOR_YELLOW:
                item_bg.setBackgroundResource(R.drawable.bg_yellow);
                item_color.check(R.id.item_color_yellow);
                break;
            case DeliveryInfo.COLOR_GREEN:
                item_bg.setBackgroundResource(R.drawable.bg_green);
                item_color.check(R.id.item_color_green);
                break;
            default:
                item_bg.setBackgroundResource(R.drawable.bg_blue);
                item_color.check(R.id.item_color_blue);
                break;
        }
        delivery.setColor(itemColor);
	}
	
	/**
	 * *********************************************************
	 * @function    selectExpressCompany      
	 * @description 
	 * @notes
	 * @author      Aliusa      
	 * @copyright   Aug 10, 2011 1:40:41 PM. All rights reserved.
	 ***********************************************************
	 */
	private void selectExpressCompany(){
	    //建立方法有3种
        //方法一，在spinner中指定数组
        //android:entries = "@array/deliveryAddition_array_expressCompany"
        //方法二,从xml读取
        //ArrayAdapter< CharSequence > adapter = ArrayAdapter.createFromResource(this, R.array.deliveryAddition_array_expressCompany, android.R.layout.simple_spinner_item);
        //方法三,使用数组
        ArrayAdapter< CharSequence > adapter = new ArrayAdapter< CharSequence >(this, android.R.layout.simple_spinner_item, ComCode.getName());
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        item_expressCompany.setAdapter(adapter);
        item_expressCompany.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                Toast.makeText(DeliveryAddActivity.this, R.string.deliveryAddition_msg_expressCompanyNullWarning, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {
                
                final String expresCompany = parent.getItemAtPosition(position).toString();
                delivery.setExpComName(expresCompany);
                delivery.setCompanyId(ComCode.getCodeByName(expresCompany));
            }});
	}
	
	/**
	 * *********************************************************
	 * @function    selecColor      
	 * @description 
	 * @notes
	 * @author      Aliusa      
	 * @copyright   Aug 10, 2011 1:40:47 PM. All rights reserved.
	 ***********************************************************
	 */
	private void selectItemColor(){
	    //set event on color check changed
        item_color.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                final int itemColor;
                switch(group.getCheckedRadioButtonId()){
                    case R.id.item_color_blue:
                        itemColor = DeliveryInfo.COLOR_BLUE;
                        item_bg.setBackgroundResource(R.drawable.bg_blue);
                        break;
                    case R.id.item_color_yellow:
                        itemColor = DeliveryInfo.COLOR_YELLOW;
                        item_bg.setBackgroundResource(R.drawable.bg_yellow);
                        break;
                    case R.id.item_color_green:
                        itemColor = DeliveryInfo.COLOR_GREEN;
                        item_bg.setBackgroundResource(R.drawable.bg_green);
                        break;
                    default:
                        itemColor = DeliveryInfo.COLOR_BLUE;
                        item_bg.setBackgroundResource(R.drawable.bg_blue);
                        break;
                }
                Logger.d("deliveryAddition", "ckeckedid="+checkedId);
                delivery.setColor(itemColor);
                
            }
        });
	}
	
	/**
	 * *********************************************************
	 * @function    setEnventOnSave      
	 * @description 
	 * @notes
	 * @author      Aliusa      
	 * @copyright   Aug 9, 2011 3:42:37 PM. All rights reserved.
	 ***********************************************************
	 */
	private void setEnventOnSave(){
	    save.setOnClickListener(new OnClickListener() {
            
	    	ProgressDialog pd;
	    	
            @Override
            public void onClick(View v) {
            	pd = new ProgressDialog(DeliveryAddActivity.this);
            	pd.cancel();
                String name = item_name.getText().toString();
                final String trackingNumber = item_trackingNumber.getText().toString().trim();
                // 检查订单是否合法
                if (trackingNumber.contains("&") || trackingNumber.contains("%") || trackingNumber.contains("?")
                        || trackingNumber.contains("\\") || trackingNumber.contains("\"")) {
                    Toast.makeText(DeliveryAddActivity.this, R.string.deliveryAddition_msg_numWrong, Toast.LENGTH_LONG).show();
                    return;
                }
                
                if (TextUtils.isEmpty(trackingNumber) 
                        ||TextUtils.isEmpty(delivery.getCompanyId())){
                    Toast.makeText(DeliveryAddActivity.this, R.string.deliveryAddition_msg_nullWarning, Toast.LENGTH_LONG).show();
                    return;
                }else{
                    if (TextUtils.isEmpty(name)){
                        final String hint = item_name.getHint().toString();
                        name = hint;
                    }
                    
                    if (DeliveryDb.getDb(DeliveryAddActivity.this).isTrackExist(delivery.getExpComName(), trackingNumber)) {
                    	Toast.makeText(DeliveryAddActivity.this, R.string.text_track_exist, Toast.LENGTH_LONG).show();
                    	return;
                    }
                    
                    delivery.setName(name);
                    delivery.setExpressNu(trackingNumber);
                    
                    Logger.d("deliveryAddition", "name="+delivery.getName()+" trackingNumber="+delivery.getExpressNu()+" expressCompany="+delivery.getCompanyId());
                }
                
                //start a new thread to download delivery info.
                pd.setMessage("处理中...");
                pd.show();
                new AsyncTask<Boolean, Boolean, Bitmap>() {

					@Override
					protected Bitmap doInBackground(Boolean... arg0) {
						return HttpClient.newInstance().checkValicode(delivery);
					}

					@Override
					protected void onPostExecute(Bitmap result) {
						if (result != null) {
							pd.dismiss();
							AlertDialog.Builder b = new AlertDialog.Builder(DeliveryAddActivity.this);
							LinearLayout ll = new LinearLayout(DeliveryAddActivity.this);
							ll.setOrientation(LinearLayout.VERTICAL);
							ll.setGravity(Gravity.CENTER);
							ImageView iv = new ImageView(DeliveryAddActivity.this);
							iv.setImageBitmap(result);
							ll.addView(iv);
							final EditText et = new EditText(DeliveryAddActivity.this);
							
							LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(200, -1);
							et.setLayoutParams(lp);
							ll.addView(et);
							b.setTitle("请输入验证码").setView(ll);
							b.setPositiveButton("确定", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface arg0, int arg1) {
									
									if ((mTrackId = insertDataToDB(delivery)) != -1){
				                        Toast.makeText(DeliveryAddActivity.this, R.string.deliveryAddition_msg_saveDone, Toast.LENGTH_SHORT).show();
				                    }else{
				                        Toast.makeText(DeliveryAddActivity.this, R.string.deliveryAddition_msg_saveWrong, Toast.LENGTH_LONG).show();
				                    }
									finish();
									
									new Thread(){
					                	public void run(){
					                		HttpClient.newInstance().updateDeliveryDetails(delivery, et.getText().toString());
					                		// update database.
					                		delivery.setId((int)mTrackId);
					                		//DeliveryDb db = new DeliveryDb(DeliveryAddActivity.this);
					                		DeliveryDb db = DeliveryDb.getDb(DeliveryAddActivity.this);
					                		//db.open();
					                		db.update(delivery);
					                		//db.close();
					                	}
					                }.start();
								}
							});
							b.create().show();
						} else {
							if ((mTrackId = insertDataToDB(delivery)) != -1){
		                        Toast.makeText(DeliveryAddActivity.this, R.string.deliveryAddition_msg_saveDone, Toast.LENGTH_SHORT).show();
		                    }else{
		                        Toast.makeText(DeliveryAddActivity.this, R.string.deliveryAddition_msg_saveWrong, Toast.LENGTH_LONG).show();
		                    }
							pd.dismiss();
							finish();
							new Thread(){
			                	public void run(){
			                		HttpClient.newInstance().updateDeliveryDetails(delivery, null);
			                		// update database.
			                		delivery.setId((int)mTrackId);
			                		//DeliveryDb db = new DeliveryDb(DeliveryAddActivity.this);
			                		DeliveryDb db = DeliveryDb.getDb(DeliveryAddActivity.this);
			                		//db.open();
			                		db.update(delivery);
			                		//db.close();
			                	}
			                }.start();
						}
						super.onPostExecute(result);
					}
                }.execute(new Boolean[]{});
//                new Thread(){
//                	public void run(){
//                		HttpClient.newInstance().updateDeliveryDetails(delivery);
//                		// update database.
//                		DeliveryDb db = new DeliveryDb(DeliveryAddActivity.this);
//                		db.updateDeliveryInfo(delivery,mTrackId);
//                		
//                	}
//                }.start();

            }
            
        });
	}
	
	
	/**
	 * *********************************************************
	 * @function    insertDataToDB
	 * @param delivery      
	 * @description 
	 * @notes
	 * @author      Aliusa      
	 * @copyright   Aug 9, 2011 3:42:40 PM. All rights reserved.
	 ***********************************************************
	 */
	private long insertDataToDB(DeliveryInfo delivery){
	    //DeliveryDb db = new DeliveryDb(this);
	    DeliveryDb   db = DeliveryDb.getDb(DeliveryAddActivity.this);
	    long trackId = -1;
	    try{
	        //db.open();
	        trackId = db.add(delivery);
	    }catch (Exception e) {
	        e.printStackTrace();
	        Logger.d("deliveryAddition", "insertDataToDB Error!!!!!!");
        }finally{
            //db.close();
        }
	    return trackId;
	}
    
}